package cn.edu.sxw.web.server.api;

import cn.edu.sxw.web.server.bean.User;
import cn.edu.sxw.web.server.service.AccountService;
import cn.edu.sxw.web.server.service.UserTokenService;
import cn.edu.sxw.web.server.service.ValidateCodeService;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@WebServlet(urlPatterns = "/api/login")
public class LoginApi extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream(), "utf-8"));
        StringBuffer jsonString = new StringBuffer();
        String line = null;
        while ((line = br.readLine()) != null) {
            jsonString.append(line);
        }

        //客户接收的数据转为json‘
        JSONObject loginJson = JSONObject.parseObject(jsonString.toString());
        //增加验证码校验
        String randomCode=loginJson.getString("randomCode");
        String validateCode=loginJson.getString("validateCode");

        ValidateCodeService validateCodeService=new ValidateCodeService();
        boolean flag=validateCodeService.validate(randomCode,validateCode);
        if(!flag){
            JSONObject error = new JSONObject();
            error.put("error", "验证码不正确");
            resp.setStatus(400);
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write(error.toJSONString());
            return;
        }
        //用户名和密码校验
        String login = loginJson.getString("login");
        String password = loginJson.getString("password");

        //调用账户数据服务
        AccountService accountService=new AccountService();
        User user=accountService.loginValidate(login,password);
        //调用登录验证方法成功获取到User对象
        if (user!=null){
            //构造token
            UserTokenService userTokenService = new UserTokenService();
            String token = userTokenService.getToken(user.getLogin());

            //返回token
            JSONObject result = new JSONObject();
            result.put("token",token);
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write(result.toJSONString());

        }else {//登录失败
            JSONObject error = new JSONObject();
            error.put("error", "用户名密码错误");
            resp.setStatus(401);
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write(error.toJSONString());
        }

    }
}
